package cn.fan.whale.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.fan.whale.entity.po.SourceEntity;
import cn.fan.whale.mapper.SourceMapper;
import cn.fan.whale.service.SourceService;
import com.alibaba.druid.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class SourceServiceImpl implements SourceService, StpInterface {

    private final SourceMapper sourceMapper;

    public SourceServiceImpl(SourceMapper sourceMapper) {
        this.sourceMapper = sourceMapper;
    }

    @Override
    public List<SourceEntity> find(SourceEntity sourceEntity) {
        return sourceMapper.selectBySelective(sourceEntity);
    }

    @Override
    public void save(SourceEntity sourceEntity) {
        Date nowDate = new Date();
        sourceEntity.setCtime(nowDate);
        sourceEntity.setMtime(nowDate);
        sourceEntity.setAvailable(1);
        sourceMapper.insert(sourceEntity);
    }

    @Override
    public void update(SourceEntity sourceEntity) {
        sourceMapper.updateByPrimaryKeySelective(sourceEntity);
    }

    @Override
    public void delete(Integer sourceId) {
        sourceMapper.deleteByPrimaryKey(sourceId);
    }

    @Override
    public List<Integer> getSourceIdListByRoleId(Integer roleId) {
        return sourceMapper.selectSourceIdListByRoleId(roleId);
    }

    @Override
    public List<SourceEntity> getSourceListByUserId(Integer userId) {
        return sourceMapper.selectWithoutBtnByUserId(userId);
    }

    @Override
    public List<String> getPermissionList(Object o, String s) {
        Integer userId = StpUtil.getLoginIdAsInt();
        List<SourceEntity> sourceEntityList = sourceMapper.selectByUserId(userId);
        List<String> result = new ArrayList<>();
        for (SourceEntity sourceEntity : sourceEntityList) {
            if (!StringUtils.isEmpty(sourceEntity.getSourceCode())) {
                result.add(sourceEntity.getSourceCode());
            }
        }
        return result;
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        return null;
    }
}
